Getting Started with Node.js


Chapter 1: The Fundamentals of Node.js

The What and Why

Let’s start at the very beginning: What exactly is Node.js? Node is usually defined as "JavaScript on backend servers". Before Node, that was not a common or easy thing. JavaScript was mainly a frontend thing. However, this definition isn’t really an accurate one because Node offers a lot more than executing JavaScript on servers. In fact, the execution of JavaScript is not done by Node at all. It’s done with a Virtual Machine (VM) like V8 or Chakra. Node is just the coordinator. It’s the one who instructs a VM like V8 to execute your JavaScript. Node is better defined as "a wrapper around a VM like V8".
V8 is Google’s open source JavaScript engine. It’s written in C++ and it’s used in Google Chrome and in Node.js. Both Chrome and Node use V8 to execute JavaScript code. V8 is the default VM in Node, but you can run Node with other VMs if you need to.
When you write JavaScript code and execute it with the node command, Node will pass your JavaScript to V8, V8 will execute that JavaScript and tell Node what the result is, and Node will make the result available to you. That’s the simple story, but Node.js is more useful than just that. Node comes with some handy, built-in modules providing easy-to-use asynchronous APIs. Let’s talk about that, and a few other reasons why developers are picking Node.js over many other options when it comes to creating services for their backends.

1) Native Modules

Node comes with feature-rich modules that make it a great platform for hosting and managing servers. These modules offer features like reading and writing files, consuming data over the network, and even compressing and encrypting data You don’t need to install these modules. They come natively packaged with Node! The big deal about these modules is that they offer asynchronous APIs that you can just use directly without worrying about threads. Yes! You can do asynchronous programming in Node and do things in parallel without needing to deal with threads. This is a big deal and it’s probably the most common benefit of using a runtime like Node. The asynchronous nature of these modules works great with VMs like V8 because these VMs are all single-threaded. This is true for both Node and Browsers. You only get a single precious thread to work with. It’s extremely important to not block that thread. For example, in your browser, if your website blocks that single thread for, say 2 seconds, the user cannot scroll up and down during these 2 seconds! In Node, if an incoming HTTP connection to your web server was handled synchronously rather than asynchronously, that’ll block the single thread, and your whole web server cannot handle any other connections while the synchronous operation is active. That’s very bad.
Working with Node’s modules and their asynchronous nature will be covered in Chapter 3.
If Node’s built-in modules were not enough for you, you can build high-performing packages using C++! Node has first-class support for C++ addons , creating dynamically linked shared objects that you can use directly with Node. Of course you can also write your addons in JavaScript if you want. Node also ships with a powerful debugger and has some other handy, generic utilities that enhance the JavaScript language and provide extra APIs (for example, to create timers, work with data types, and process arrays and objects). Even if you don’t want to host your backend servers in Node, having the powerful, built-in features — and the ease to add more — makes Node a great platform for tools to work with other applications and enhance your work flow. Why React Developers LOVE Node Some people mistakenly assume that Node is required in order to use React. It is not. You don’t need Node to run a… edgecoders.com

2) A Package Manager and a Dependency Manager

Node ships with a powerful package manager (which is called NPM). We did not have a package manager in the JavaScript world before Node. NPM was nothing short of revolutionary. It changed the way we work and share JavaScript. Node was the enabler of this because NPM ships natively with Node. NPM is basically the world’s largest collection of FREE and reusable code. You can make a feature-rich Node application just by using code that’s freely available on NPM. NPM is a reliable package manager which comes with a simple CLI (the npm command). The npm command makes it really easy to install third-party packages, share your own code, and reuse your own code. In addition, the NPM registry, where the packages get hosted, has so many options. By "so many", I mean hundreds of thousands of options of FREE tools that you can just install and use on your Node servers. The other big thing about Node is that it comes with a reliable module dependency manager (different than NPM). This module dependency manager is also another thing that we did not have in the JavaScript world.
experimentally-supported in Node.js as well.
Node’s module dependency manager has been available since Node was released and it opened the door to so much flexibility in how we code JavaScript! It is widely used, even for JavaScript that gets executed in the browser, because NPM has many tools to bridge the gap between modules written in Node and what browsers can work with today. NPM and Node’s module system together make a big difference when you work with any JavaScript system, not just the JavaScript that you execute on backend servers or web browsers. For example, if you have a fancy fridge monitor that happens to run on JavaScript, you can use Node and NPM for the tools to package, organize, and manage dependencies, and then bundle your code, and ship it to your fridge!

3) One Language to Rule Them All

By using Node, you’re committing to the flexible JavaScript language, which is used on every website today. It is the most popular programming language and that statement will continue to be true for decades to come. Despite its problems, JavaScript is actually a good language today. You don’t hate JavaScript But something else might make you think you do edgecoders.com With Node, you get to have a single language across the full-stack. You use JavaScript in the browser and you use it for the backend as well. There are some subtle but great benefits to that:

There will be dragons

Node is not all rainbows and unicorns. It has some disadvantages, which are interestingly the same advantage points if you just look at them with different bias. For example, Node’s asynchronous non-blocking nature is just a completely different model of thinking and reasoning about code. If you’ve never done it before, it is going to feel weird at first. You need time to get your head wrapped around this model and to get used to it. Having a big package registry offering many options means that for every single thing you need to do you have many options to pick from, and some people hate that. You need to constantly research these options and make a mental effort to pick the "better" ones. These options usually have big differences and you might end up spending a lot of time researching them. Also, NPM along with Node’s module manager enabled shipping smaller and smaller code. This means you need to use more and more packages. It’s not unusual for a Node application to use 300 or more packages. This is both a good thing and a bad thing depending on who you ask. I think it’s a good thing. Smaller packages are easier to control, maintain, and scale, but you do have to make peace with the fact that you’ll be using a lot of them.
Smaller code is actually why Node is named Node! In Node, we build simple small single-process building blocks (nodes) that can be organized with good networking protocols, to have them communicate with each other and scale up to build large, distributed programs.

Node’s REPL Mode

Let’s explore the node command. When you type the node command without a script for it to execute, Node will start a REPL session. REPL stands for Read, Eval, Print, Loop. It’s a very convenient way to quickly test simple JavaScript and Node commands. You can type any JavaScript code in the REPL. For example, type Math.random() and then, press Enter:
Node’s REPL
Node will Read your line, Evaluate it, Print the result, and Loop over these 3 things until you exit the session (which you can do with a CTRL+D). Note how the Print step happened automatically. We didn’t need to add any instructions to print the result. Node will just print the result of each line you type. This is cool, but keep in mind that some lines will not have any results at all. The Node REPL will print "undefined" in that case. For example, if you typed:
let answer = 42;
This is a statement in JavaScript. It’s not an expression. It does not have any output. When you hit Enter, you’ll see that the REPL prints undefined as the output of this statement. Don’t let that confuse you. On the other hand, if you type an expression, for example:
3 == '3'
This is a Boolean expression. The REPL will print its result for you: Sometimes, the expression that you need to test might need multiple lines. For example, say that you want to define a function that generates today’s date and test it out. You’ll start with the function name and begin with a curly brace. You hit Enter there: The Node’s REPL is smart enough to detect that your code is not done yet and it will go into a multi-line mode for you to type more. If you finish a valid function definition, you’ll get out of this multiline mode: This REPL multi-line mode is limited. Node has a more featured editor right inside the REPL. You type .editor to open it up and when you do, you can type as many lines as you need. For example, you can define multiple functions or paste code from the clipboard: When you are done typing, you hit Control+D to have the REPL evaluate your code. All the functions you defined in the editor will be available in your REPL session. The .editor command is a REPL special command. There are a few other special commands. You can see the list by typing the .help command: The .break command (or its .clear alias) lets you get out of some weird cases in a REPL session. For example, when you paste some code in Node’s multi-line mode and you are not sure how many curly braces you need to get to an executable state. You can discard your pasted code by using a .break command. This saves you from killing a session to get yourself out of simple situations like this one. The .load and .save commands can be used to generate and use external Node scripts inside your REPL. This can be a great time saver.

Use The TAB Key!

I need to emphasize the importance of the TAB key. If you are not familiar with this powerful key, you’re in for a treat! The TAB character itself is not a useful one, but the TAB key is the driver of a very powerful feature called TAB-Completion. You might be familiar with that feature in your code editor, but I’d like you to also be aware that it works inside Node’s REPL as well. A single TAB in Node’s REPL can be used for autocompletion, and a double TAB (which is pressing the TAB key twice) can be used to see a list of possible things you can type from whatever partially-typed string you have. For example. If you type the character c and then double TAB on that, you’ll see all the possible keywords and functions that start with c : If you single TAB on something that matches only a single option, it’ll be auto-completed. For example, crypto in the list above is the only keyword that begins with cr. So, if you single TAB after typing cr, crypto will be auto-completed. This is not about being lazy and not wanting to type the whole thing. The usefulness of this TAB-Completion is about avoiding typing mistakes and discovering what is available. This latter point is important. For example, say I want to know what API functions and properties I can use on the Array class. I can type Array and then I can type the . character and double TAB after that:
All the functions and properties that can be used from the Array class.
TAB-Completion also works on objects. If you have an array object in the REPL session, you can use the same . character then double TAB trick to get a list of all the methods available on that object:
Can’t remember the name of a method you need? TAB-Completion can help.
The TAB-completion discoverability works anywhere within the REPL session. For example, you can see the special dot commands by double tabbing on a single . character: This discoverability also works on the global level itself. If you double TAB on an empty line, everything that is globally available in Node appears. This is a big list, but it’s a useful one: In this list, you can see all the common globals in the JavaScript language itself, which you’re probably familiar with, like Array, Number, String , and Object classes, built-in libraries like Math and JSON , and some other top-level functions. This list also has the globals that are available in the Node runtime itself. A few of these are truly globals in Node, like the Buffer class, the process object, and the various functions to set and clear timers. The lowercase variables in this list (like dns, net, cluster, http , …) represent the built-in modules in Node. These are the powerful libraries that you get out of the box. Note that these are available directly in a REPL session, but when working with a regular Node script, you will need to require these modules first to be able to use them. One of the useful REPL’s features that you can see in the list above is the _ (underscore) variable. This is similar to the $? feature in Bash. It stores the value of the last successfully-evaluated expression. For example, say that you executed a Math.random() call, and after you did, you wanted to put that same value in a constant. You can do that with _ because it automatically stores the last value.

Node’s Hello World Example

Here is Node’s version of a "Hello World" example:
// server.js
const http = require('http');                        // 1


const server = http.createServer((req, res) => {     // 2

  res.end('Hello World\n');                          // 3


});                                                  // 4


server.listen(4242, () => {                          // 5

  console.log('Server is running...');               // 6


});                                                  // 7
This script represents a simple Web server. You don’t need to install anything to run this script. This is all Node’s built-in power. To execute a script with Node, you just specify the location of that script as the argument for the node command. The location can be absolute or relative (to where you are invoking the node command).
$ node relative/or/absolute/path/to/server.js
If you just provide a file name, the node command will look for that file in the current working directory. If the script has a running task (like a Web server listening for connections, for example), then Node will continue running. Let’s decipher the simple web server example… Line #1 uses the require function. This is the first thing you need to learn about Node’s internal. The require function is what you use to manage the dependencies of your programs. You can use require to depend on a library, whether this library is a built-in one (like the http one the example is using) or a 3rd-party installed one (like express which you can get with NPM). This web server example depends on the built-in http module. It’s the module that has the feature of creating a web server. There are many other libraries that you can use to create a web server, but this one is built-in. You don’t need to install anything to use it, but you do need to require it.
In a Node’s REPL session, built-in modules (like http) are available immediately without needing to require them. This is not the case with executable scripts. You can’t use any dependencies (including built-in ones) without requiring them first.
Line #2 creates a server constant by invoking the createServer function on the http module. This function is one of many functions that are available under the http module’s API. You can use it to create a web server object. It accepts an argument that is known as the Request Listener. The request listener is a simple function that Node will invoke every time there is a request to the web server. This why this listener function receives the request object as an argument (named req above but you can name it whatever you want). The other argument this listener function receives, named res in the example, is a response object. It’s the other side for a request connection. We can use the res object to write things back to the requester. It’s exactly what our simple web server is doing. It’s writing back — using the .end method — the "Hello World" string.
.end method can be used as a shortcut to write data and then end the request in one line. We will be talking more about the http module in Chapter 5.
The createServer function only creates the server object. It does not activate it. To activate this web server, you need to invoke the listen function on the created server (line #5). The listen function accepts many arguments, like what OS port and host to use for this server. The last argument for it is a function that will be invoked once the server is successfully running on the specified port. The example above just logs a message to indicate that the server is running successfully at that point. Execute the server.js script above using the node command. While the server is running, if you go to a browser and ask for an http connection on localhost with the port that was used in the script (4242 in this case), you will see the Hello World string that this example had in its request listener function.